package com.huaqin.punan.headset;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.io.File;

/**
 * Created by punan on 5/21/13.
 */
public class HeadsetActionServices extends Service {
    public static final String TAG = "HeadsetActionServices";

    public IBinder onBind(Intent intent) {
        return null;
    }

    private BroadcastReceiver HeadsetReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            int state = intent.getIntExtra("state",-1);  //0 no, 1 has headset
            String name = intent.getStringExtra("name"); //headset type
            int mic = intent.getIntExtra("microphone",-1); //0 no, 1 has mic

            Log.i(TAG, "action: " + action);
            Log.d(TAG,"state: "+state);
            Log.d(TAG,"name: "+name);
            Log.d(TAG,"mic: "+mic);


            if("android.intent.action.HEADSET_PLUG".equals(action) && state == 1){
                /*
                Intent MusicIntent = new Intent();
                MusicIntent.setAction(Intent.ACTION_VIEW);
                MusicIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                File file = new File("");
                MusicIntent.setDataAndType(Uri.fromFile(file),"audio/*");
                context.startActivity(MusicIntent);
                */

                /*
                Intent MusicIntent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
                MusicIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(MusicIntent);
                */

                Intent MusicIntent = new Intent();
                MusicIntent.setClass(HeadsetActionServices.this,AppPickerDialog.class);
                MusicIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                HeadsetActionServices.this.startActivity(MusicIntent);

            }


            //Toast.makeText(context, "action=" + action + "\nstate=" + state + "\nname=" + name + "\nmic=" + mic, Toast.LENGTH_LONG).show();

        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

        IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);

        registerReceiver(HeadsetReceiver, receiverFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        unregisterReceiver(HeadsetReceiver);
    }
}
